<template>
  <div class="carousel">
    <div
      class="carousel-side"
      :style="{
        transform: `translateX(${index * -100}%)`,
        transition: index === 0 ? 'none' : 'transform 0.5s linear',
      }"
    >
      <div
        class="carousel-item"
        v-for="(item, i) in carouselData"
        :key="i"
        @touchstart="handleTouchStart"
        @touchend="handleTouchEnd"
      >
        <img :src="item.imgUrl" alt="" />
      </div>
    </div>
  </div>
  <div class="carousel-controls">
    <div
      v-for="i in carouselData.length"
      :class="index === i - 1 ? 'active-control' : ''"
      @click="index = i - 1"
      :key="i"
    ></div>
  </div>
</template>

<script>
export default {
  props: {
    carouselData: {
      type: Array,
      default: () => [],
    },
    activeIndex: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      index: 0,
      startX: 0,
    };
  },
  mounted() {
    this.index = this.activeIndex;
    setInterval(() => {
      this.index = (this.index + 1) % this.carouselData.length;
    }, 3000);
  },
  methods: {
    handleTouchStart(event) {
      this.startX = event.touches[0].clientX;
    },
    handleTouchEnd(event) {
      let deltaX = event.changedTouches[0].clientX - this.startX;
      if (deltaX > 0) {
        this.index--;
        if (this.index < 0) {
          this.index = this.carouselData.length - 1;
        }
      } else {
        this.index++;
        if (this.index >= this.carouselData.length) {
          this.index = 0;
        }
      }
      this.startX = 0;
    },
  },
};
</script>

<style scoped lang="scss">
.active-control {
  background-color: rgb(110, 212, 71) !important;
  width: 5.333333vw !important;
  height: 2.666667vw !important;
  border-radius: 1.333333vw !important;
  margin: 0 1.333333vw !important;
}
.carousel-controls {
  z-index: 1000;
  display: flex;
  justify-content: center;
  -webkit-transform: translateY(-5.333333vw);
  -moz-transform: translateY(-5.333333vw);
  -ms-transform: translateY(-5.333333vw);
  -o-transform: translateY(-5.333333vw);
  transform: translateY(-5.333333vw);
  & > div {
    width: 2.666667vw;
    height: 2.666667vw;
    border-radius: 50%;
    border: 1px solid #ccc;
    margin: 0 1.333333vw;
    background-color: #a79b97;
  }
}
.carousel {
  width: 100vw;
  height: 69.333333vw;
  overflow: hidden;
  .carousel-side {
    display: flex;
  }
  img {
    width: 100vw;
    height: 69.333333vw;
    border-radius: 4vw;
    object-fit: cover;
  }
}
</style>
